<template>
  <div class="body_bgi full relative">
    <!-- 活动已开始 -->
    <div class="w_full h_full text_center absolute_center p_20 relative" v-if="!isActivityStart">
      <div class="fs_2rem main_text ls_5 font_zh mt_180">{{ contestName }}比赛</div>
      <div class="fs_1rem mt_20 color_888">欢迎您参与本次活动</div>

      <div class="w_full ph_20 mt_50 absolute left_0 bottom_50">
        <van-button 
          round block type="primary" size="large" 
          color="linear-gradient(to bottom, #f7e0cf, #fa964e)"
          @click="getCurrentSheep(roomId)">开始评分
        </van-button>
      </div>
    </div>

    <!-- 活动已开始 -->
    <div class="score_form h_full-50 ph_10 scroll_box overflow_y_auto" v-if="isActivityStart">
      <div class="fs_1_5rem main_color ls_5 text_center font_zh pt_20">{{ contestName }}比赛</div>
      <div class="w_full text_center fs_22 p_5">
        <div 
          class="font_number fs_70 main_text" 
          v-if="!isScore && sheepInfo && sheepInfo.sheepNumber"
        >
          {{ showSheepNumber }}<span class="pl_10 fs_1rem color_888">参赛羊</span> 
        </div> 
        <div class="font_number fs_70 main_text" v-if="isScore">
          {{ scoredSheepNumber }}<span class="pl_10 fs_1rem color_888">参赛羊</span> 
        </div> 
      </div>

      <van-form v-if="!isScore">
        <van-field
          readonly
          clickable
          name="体型外貌"
          label="体型外貌："
          label-width="100"
          :value="scoreForm.tiXing"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('tiXing')"
          :rules="[{required: true }]"
        />
        <van-field
          readonly
          clickable
          name="密度"
          label="密度："
          label-width="100"
          :value="scoreForm.density"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('density')"
          :rules="[{required: true }]"
        />
        
        <van-field
          readonly
          clickable
          name="弯曲度"
          label="弯曲度："
          label-width="100"
          :value="scoreForm.wanQu"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('wanQu')"
          :rules="[{required: true }]"
        />
        <van-field
          readonly
          clickable
          name="油汗"
          label="油汗："
          label-width="100"
          :value="scoreForm.oilSweat"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('oilSweat')"
          :rules="[{required: true }]"
        />
        <van-field
          readonly
          clickable
          name="均匀度"
          label="均匀度："
          label-width="100"
          :value="scoreForm.uniformity"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('uniformity')"
          :rules="[{required: true }]"
        />
        <van-field
          readonly
          clickable
          name="腹毛"
          label="腹毛："
          label-width="100"
          :value="scoreForm.fuMao"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('fuMao')"
          :rules="[{required: true }]"
        />
        <van-popup v-model="isShowPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="pickerColumns"
            @confirm="confirmPicker"
            @cancel="isShowPicker = false"
          />
        </van-popup>

        <div class="m_20">
          <van-button
            round block type="info" size="large" native-type="submit"
            color="linear-gradient(to bottom, #f7e0cf, #fa964e)"
            @click="clickSubmit()">提交评分</van-button>
        </div>
      </van-form>

      <!-- 提交完成后 等待评分 -->
      <div class="w_full h_full-350 ph_10" v-else>
        <div class="w_full h_50 lh_50 text_center fs_1_5rem main_text fw_bold">
          您的评分: <span class="">{{ my.totalScore }} 分</span> 
        </div>

        <div class="w_full h_full-200 scroll_box overflow_y_auto bgc_fff border_radius_10 mt_10">
          <!-- <div 
            class="w_full h_60 lh_60 border_b_1_s_eee" 
            v-for="(item, index) in scoreList" :key="index"
            @click="showScoreDetail(item)"
          >
            <div class="w_full flex_row_between ph_30 bgc_orange color_fff fs_22" v-if="item && item.judgeId == my.judgeId">
              <div>{{ index + 1 }}</div>
              <div>我</div>
              <div>评分：{{ item.totalScore }} </div>
            </div>

            <div class="w_full flex_row_between ph_30 fs_22" v-else>
              <div>{{ index + 1 }}</div>
              <div>评委: {{ item.judgeId }} </div>
              <div>评分：{{ item.totalScore }} </div>
            </div>
          </div> -->

          <div class="w_full h_50 lh_50 border_b_1_s_ccc ph_20 fs_1rem flex_row_between">
            <div class="w_50_p text_left pl_0">体型：</div><div class="w_50_p pl_20 text_right">{{ my.tiXing }}</div>
          </div>
          <div class="w_full h_50 lh_50 border_b_1_s_ccc ph_20 fs_1rem flex_row_between">
            <div class="w_50_p text_left pl_0">密度：</div><div class="w_50_p pl_20 text_right">{{ my.density }}</div>
          </div>
          <div class="w_full h_50 lh_50 border_b_1_s_ccc ph_20 fs_1rem flex_row_between">
            <div class="w_50_p text_left pl_0">弯曲度：</div><div class="w_50_p pl_20 text_right">{{ my.wanQu }}</div>
          </div>
          <div class="w_full h_50 lh_50 border_b_1_s_ccc ph_20 fs_1rem flex_row_between">
            <div class="w_50_p text_left pl_0">油汗：</div><div class="w_50_p pl_20 text_right">{{ my.oilSweat }}</div>
          </div>
          <div class="w_full h_50 lh_50 border_b_1_s_ccc ph_20 fs_1rem flex_row_between">
            <div class="w_50_p text_left pl_0">均匀度：</div><div class="w_50_p pl_20 text_right">{{ my.uniformity }}</div>
          </div>
          <div class="w_full h_50 lh_50 border_b_1_s_ccc ph_20 fs_1rem flex_row_between">
            <div class="w_50_p text_left pl_0">腹毛：</div><div class="w_50_p pl_20 text_right">{{ my.fuMao }}</div>
          </div>
        </div>

        <div class="w_full h_100 lh_100 p_20">
          <van-button 
            round block type="primary" size="large" 
            color="linear-gradient(to bottom, #f7e0cf, #fa964e)"
            @click="reloadSheepScoreList()">刷新
          </van-button>
        </div>

        <!-- <div class="w_full h_100 lh_100 p_20">
          <van-button 
            round block type="primary" size="large" 
            color="linear-gradient(to bottom, #f7e0cf, #fa964e)"
            @click="">请等待
          </van-button>
        </div> -->
      </div>
    </div>
    
    <!-- 确认提交表单 ？ -->
    <van-dialog v-model="isShowDialog" title="确认提交评分？" show-cancel-button @confirm="submitScoreForm">
      <div class="w_full ph_10 mv_20 fs_1rem">
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">体型：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreForm.tiXing }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">密度：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreForm.density }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">弯曲度：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreForm.wanQu }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">油汗：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreForm.oilSweat }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">均匀度：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreForm.uniformity }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">腹毛：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreForm.fuMao }}</div>
        </div>

        <div class="w_full flex_row_start flex_center pb_10 pt_10 border_t_1_s_ccc color_0bfb83 fs_20 fw_bold">
          <div class="w_50_p pr_5 text_right">总分：</div>
          <div class="w_50_p pl_5">{{ scoreForm.tiXing + scoreForm.density + scoreForm.wanQu + scoreForm.oilSweat + scoreForm.uniformity + scoreForm.fuMao }}</div>
        </div>
      </div>
    </van-dialog> 

    <!-- 查看评分信息 -->
    <van-dialog v-model="isShowsScoreDetailDialog" :title="formatScoreDetailTitle(scoreDetailForm)" show-cancel-button @confirm="isShowsScoreDetailDialog=false">
      <div class="w_full ph_10 mv_20 fs_22">
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">体型：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreDetailForm.tiXing }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">密度：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreDetailForm.density }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">弯曲度：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreDetailForm.wanQu }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">油汗：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreDetailForm.oilSweat }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">均匀度：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreDetailForm.uniformity }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">腹毛：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreDetailForm.fuMao }}</div>
        </div>
      </div>
    </van-dialog> 

    <!-- 评分标准 dialog -->
    <van-dialog 
      v-model="isShowRuleDialog" 
      :title="contestName + '比赛评分标准'" 
      show-cancel-button 
      cancelButtonText="关闭"
      confirmButtonText="知道了" 
      @confirm="isShowRuleDialog=false"
    >
      <div class="w_full h_80_p scrool_box overflow_y_auto p_20 fs_1rem"> 
        <p v-html="rule"></p>
      </div>
    </van-dialog> 

    <!-- webscoket 链接 状态 -->
    <div class="w_50_p h_30 absolute left_0 bottom_10 color_ccc pl_10 fs_1rem">网络 {{ formatWebSocketState() }}</div>
    <div 
      class="w_100 h_30 lh_30 text_center fs_1rem bgc_0000003a border_radius_5 absolute bottom_10 right_10 main_color"
      @click="showRule()">评分标准
    </div> 
  </div>
</template>

<script>
  import {
    getCurrentSheep,
    saveSheepScore,
    getSheepScoreDetail,
    getGuiZe
  } from '@/api/index.js'

  import ws2 from "@/util/websocket2"
  import { Toast, Dialog } from 'vant';

  export default {
    name: 'SheepScore',
    data() {
      return {
        // appId: 36758403,
        // server: "wss://webliveroom36758403-api.imzego.com/ws",
        token: "",
        webSctMsg: null,
        webSctState: null,

        isActivityStart: false,

        activeFormItem: null,

        isShowPicker: false,
        pickerColumns: [],

        scoreForm: {
          tiXing: null,
          density: null,
          wanQu: null,
          oilSweat: null,
          uniformity: null,
          fuMao: null
        },
        
        contestId: null,
        contestName: '',
        roomId: null,
        sheepInfo: {},
        currentSheepUpdate: false,

        isScore: false,
        isShowDialog: false,

        scoredSheepNumber: null,
        isScoreFinished: false,
        my: {},
        scoreList: [],

        isShowsScoreDetailDialog: false,
        scoreDetailForm: {},

        timer: null,
        isShowRuleDialog: false,

        rule: ''
      }
    },
    computed: {
      showSheepNumber() {
        if (this.sheepInfo.sheepNumber) {
          return this.sheepInfo.sheepNumber
        }
      }
    },
    async mounted() {
      let roomId = this.$route.params.roomId
      let contestId = this.$route.params.contestId
      let contestName = this.$route.params.contestName
      
      this.roomId = roomId
      this.contestId = contestId
      this.contestName = contestName

      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }

      var websocket_state = window.sessionStorage.getItem('websocket_state')
      if (!websocket_state || websocket_state != 1) {
        let token = window.sessionStorage.getItem('token')
        // let roomId = window.sessionStorage.getItem('roomId')

        if (token && roomId) {
          // 链接 webSocket
          this.connectWebSocket(token, roomId)       
        } else {
          console.log('weocsecket 缺少链接参数！');
        }
      }   

      window.addEventListener('beforeunload', e => {
        console.log('浏览器将要刷新');

        // 断开 websocket 链接 状态
        window.sessionStorage.setItem('websocket_state', 2)
      })
    },

    destroyed() {
      clearInterval(this.timer)
      this.timer = null

      // 断开 websocket 链接 状态
      window.sessionStorage.setItem('websocket_state', 2)
    },

    methods: {
      // 链接 webSocket 
      connectWebSocket(token, roomId) {
        ws2.init(
          // `ws://192.168.9.87:8133/ws?token=${token}&roomId=${roomId}`,
          // `ws://192.168.31.88:8144/ws?token=${token}&roomId=${roomId}`,
          // `ws://xmy.5mus.com/api/ws?token=${token}&roomId=${roomId}`,
          `ws://192.168.138.143:8144/ws?token=${token}&roomId=${roomId}`,
          this.token,
          data => {
            try {
              var msg = JSON.parse(data)

              this.webSctMsg = msg

              // 投票界面上 更新 羊的 基本信息
              if (msg.type == 'SheepEntity') {
                if (this.timer) {
                  clearInterval(this.timer)
                  this.timer = null
                }

                // 获取房间中的 当前羊
                this.getCurrentSheep(roomId)

                if (this.isScore) {
                  // 评分状态下 显示，更新界面倒计时， 倒计时结束后 更新界面
                  this.countDown()
                }
              } else if (msg.type == 'SaveSheepScore') {
                if (this.timer) {
                  clearInterval(this.timer)
                }
                
                // 获取 评分详情
                this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)
              }
            } catch (err) {
              this.$message.error(err)
            }
          },
          state => {
            console.log("state changed !");

            this.webSctState = state
          }
        )

        window.sessionStorage.setItem('sock', ws2.wsObj)
      },

      // 校验输入的 值
      valideValue2(val) {
        return 8 <= val && val <= 32
      },

      // 选择 值
      selectValue(form) {
        this.activeFormItem = form

        // 密度
        if (form == 'tiXing'){
          this.pickerColumns = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
        } else if (form == 'density') {
          this.pickerColumns = [10, 8, 6]
        } else if (form == 'wanQu') {
          this.pickerColumns = [2, 1]
        } else if (form == 'oilSweat') {
          this.pickerColumns = [3, 1, 0]
        } else if (form == 'uniformity') {
          this.pickerColumns = [2, 0]
        } else if (form == 'fuMao') {
          this.pickerColumns = [2, 1]
        } else {
          this.pickerColumns = []
        }

        this.isShowPicker = true
      },

      confirmPicker(val) {
        this.scoreForm[this.activeFormItem] = val
        this.isShowPicker = false
      },

      // 获取 房间中的 当前羊
      async getCurrentSheep(roomId, current_sheep_id) {
        let res = await getCurrentSheep(roomId)
        try {
          if (res.code == 1000 && res.data.sheepNumber) {
            this.isActivityStart = true

            if (current_sheep_id) {
              this.currentSheepUpdate = res.data.id == current_sheep_id ? false : true
            }
           
            this.sheepInfo = {}
            this.sheepInfo = res.data

            // 如果 当前羊 已评分？ 显示 评分结果界面
            if (res.data.isScore) {
              Toast.success({ duration: 2000,  message: '已完成评分！' })
              this.isScore = res.data.isScore

              // 获取 评分详情
              this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)

              if (this.timer == null) {
                this.timer = setInterval(() => {
                  // 获取 评分详情
                  this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)
                }, 2000)
              }
            } else {
              // Toast.success({ duration: 2000,  message: '请开始评分！' })
            }
          } else {
            Toast.loading({
              duration: 2000,
              message: '请等待羊登场'
            })
          }
        } catch(err) {
          console.log('获取房间中的当前羊失败 : ', err);
        }
      },

      // 点击【提交】按钮， 显示确认框
      clickSubmit() {
        let validateResult = this.validateScoreForm()

        validateResult ? this.isShowDialog = true : Toast.fail('请检查表单！');
      },

      // 验证表单 内容
      validateScoreForm() {
        let result = ''
        for (let i in this.scoreForm) {
          if (this.scoreForm[i] === null) {
            result = false
            return 
          } else {
            result = true
          }
        }

        return result
      },

      // 点击 【确定】
      submitScoreForm() {
        let params = {
          contestId: parseInt(this.contestId),
          rfid: this.sheepInfo.rfid,
          roomId: parseInt(this.roomId),
          tiXing: parseInt(this.scoreForm.tiXing),
          density: parseInt(this.scoreForm.density),
          wanQu: parseInt(this.scoreForm.wanQu),
          oilSweat: parseInt(this.scoreForm.oilSweat),
          uniformity: parseInt(this.scoreForm.uniformity),
          fuMao: parseInt(this.scoreForm.fuMao)
        }

        this.saveSheepScore(params)
      },

      // 提交评分
      async saveSheepScore(params) {
        let res = await saveSheepScore(params)
        try {
          if (res.code == 1000 && res.message == 'success') {
            Toast.success('提交成功！');
            this.isScore = true

            // 获取 评分详情
            this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)

            if (!this.timer) {
              this.timer = setInterval(() => {
                // 获取 评分详情
                this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)
              }, 2000)
            }
          } else if (res.code == 1001 && res.message == '参赛羊不存在') {
            Toast.fail('参赛羊不存在！');
          }
        } catch(err) {
          console.log('羊评分提交失败 : ', err);
        }
      },

      // 获取 羊 评分详情
      async getSheepScoreDetail(contestId, rfid) {
        let res = await getSheepScoreDetail(contestId, rfid)
        try {
          if (res.code == 1000 && res.message == 'success') {
            this.scoredSheepNumber = res.data.sheepNumber
            this.isScoreFinished = res.data.isFinished
            this.my = res.data.mySheepScore
            this.scoreList = res.data.sheepScoreList

            // 评委 数量
            if (res.data.isFinished) {
              clearInterval(this.timer)
              this.timer = null
            }                       
          }
        } catch(err) {
          console.log('获取羊的评分信息失败 : ', err);
        }
      },

      // 查看评分详情
      showScoreDetail(item) {
        this.isShowsScoreDetailDialog = true

        this.scoreDetailForm = item
      },

      // 格式化 评分详情 title
      formatScoreDetailTitle(obj) {
        if (obj.judgeId) {
          let str = ''
          
          if (this.my.judgeId && obj.judgeId == this.my.judgeId) {
            str = '我'
          } else {
            str = `评委${obj.judgeId}`
          }

          return `${str} 的评分信息`
        }
      },

      // 评委 手动切换 当前羊的评分结果
      reloadSheepScoreList() {
        if (!this.isScoreFinished) {
          // 获取 评分详情
          this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)

          Toast.success({
            duration: 2000,
            message: '刷新成功！'
          })
        } else {
          // 获取房间中的 当前羊
          this.getCurrentSheep(this.roomId, this.sheepInfo.id)

          if (this.currentSheepUpdate) {
            this.countDown()
          } else {
            Toast.fail('请稍后...');
          }
        }
      },

      updateWebsocketSheep() {
        this.scoreForm = {
          tiXing: null,
          density: null,
          wanQu: null,
          oilSweat: null,
          uniformity: null,
          fuMao: null
        }

        this.activeFormItem = null
        this.pickerColumns = []

        this.scoredSheepNumber = null
        this.isScoreFinished = false
        this.my = null
        this.scoreList = []

        this.isShowsScoreDetailDialog = false
        this.scoreDetailForm = {}
      },

      // 倒计时
      countDown() {
        const toast = Toast.loading({
          duration: 0, 
          forbidClick: true,
          message: '',
        });

        let second = 2;
        let _this = this
        let timerX = setInterval(() => {
          if (second) {
            toast.message = `${second} 秒后更新`;
            second--;
          } else {
            _this.isScore = false

            // 清空 评分结果
            _this.updateWebsocketSheep()

            // 手动清除 Toast
            Toast.clear();

            if (timerX) {
              clearInterval(timerX);
              timerX = null
            }
          }
        }, 1000);
      },

      // 显示 websocket 链接 状态
      formatWebSocketState() {
        let websocket_state = window.sessionStorage.getItem('websocket_state')
        let result = ''
        if (websocket_state == 1) {
          result = '已连接'
        } else {
          result = '链接异常'
        }
        return result
      },

      showRule() {
        this.getGuiZe(this.contestId)

        this.isShowRuleDialog = true
      },

      // 获取 评分规则
      async getGuiZe(contestId) {
        let res = await getGuiZe(contestId)
        try {
          if (res.code == 1000 && res.message == 'success') {
            this.rule = res.data.guiZeContent
          }
        } catch(err) {
          console.log('获取评分规则失败 : ', err);
        }
      }
    }
  }
</script>

<style>
  .score_form > .van-form > .van-cell::after { left: 0; right: 0; }
  .score_form > .van-form > .van-cell:nth-child(1) {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
  }
  .score_form > .van-form > .van-cell:nth-last-child(2) {
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
  }

  .van-button--large { height: 60px; }

  .van-cell__title > span { font-size: 1rem !important; }
  .van-cell { padding: 20px 10px; }
  .van-field__body > input { font-size: 1rem !important; }
  .van-dialog__header { font-size: 1rem !important; }
  .van-button__text { font-size: 1rem !important; }
</style>